﻿<template>
	<transition name="el-zoom-in-center">
		<div class="SHZY-preview-main">
			<div class="SHZY-common-page-header">
				<el-page-header @back="goBack" :content="!dataForm.id ? '新建' : '编辑'" />
				<div class="options">
					<el-button v-if="!readOnly" type="primary" @click="dataFormSubmit(0)" :loading="btnLoading">保
						存</el-button>
					<el-button v-if="!readOnly" type="primary" @click="dataFormSubmit(1)" :loading="btnLoading">提
						交</el-button>
					<el-button @click="goBack">取 消</el-button>
				</div>
			</div>
			<div :style="{ margin: '0 auto', width: '100%' }">
				<el-row :gutter="15" class=" main">
					<el-form :disabled="readOnly" ref="elForm" :model="dataForm" size="small" label-width="110px"
						label-position="right" :rules="rules">
						<el-col :span="24">
							<el-form-item label="工单号" prop="code">
								<el-input v-model='dataForm.code' placeholder='请输入' clearable required
									:style='{ "width": "100%" }' maxlength='50'>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="工单类型" prop="type">
								<el-select v-model='dataForm.type' placeholder='请选择' clearable required
									:style='{ "width": "100%" }'>
									<el-option v-for="(item, index) in workOrderTypeData" :key="index"
										:label="item.fullName" :value="item.enCode"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="物料ID" prop="materialId">
								<SHZY-select :list="materialData" v-model:bindValue="dataForm.materialId"
									:style='{ "width": "100%" }' label="name" value="id" placeholder="请选择物料" isConcat
									concatSymbol=" / ">
								</SHZY-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="数量" prop="qty">
								<el-input v-model='dataForm.qty' placeholder='请输入' clearable required
									:style='{ "width": "100%" }'>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="单位" prop="unit">
								<el-select v-model='dataForm.unit' placeholder='请选择' clearable :style='{ "width": "100%" }'>
									<el-option v-for="(item, index) in unitData" :key="index" :label="item.fullName"
										:value="item.enCode"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="计划开始时间" prop="planStartTime">
								<el-date-picker v-model='dataForm.planStartTime' placeholder='请选择' clearable required
									:style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
									value-format='timestamp'>
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="计划完成时间" prop="planEndTime">
								<el-date-picker v-model='dataForm.planEndTime' placeholder='请选择' clearable required
									:style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
									value-format='timestamp'>
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注" prop="remark">
								<el-input v-model='dataForm.remark' placeholder='请输入' show-word-limit
									:style='{ "width": "100%" }' type='textarea' :autosize='{ "minRows": 4, "maxRows": 4 }' maxlength='500'>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label-width="0">
								<div class="SHZY-common-title">
									<h2>物料详情</h2>
								</div>
								<el-form ref="tableForm" :model="dataForm" :rules="tableRules">
									<el-table :data="dataForm.qmsBusiWorkorderdetailList" size='mini'>
										<el-table-column type="index" width="50" label="序号" align="center" />
										<el-table-column prop="materialId" label="物料">
											<template slot-scope="scope">
												<el-form-item :prop="'qmsBusiWorkorderdetailList.' + scope.$index + ''"
													:rules="tableRules.materialId">
													<SHZY-select :list="materialData"
														v-model:bindValue="scope.row.materialId"
														:style='{ "width": "100%" }' label="name" value="id"
														placeholder="请选择物料" isConcat concatSymbol=" / ">
													</SHZY-select>
												</el-form-item>
											</template>
										</el-table-column>
										<el-table-column prop="qty" label="用量" width="200">
											<template slot-scope="scope">
												<el-form-item :prop="'qmsBusiWorkorderdetailList.' + scope.$index + '.qty'"
													:rules="tableRules.qty">
													<el-input v-model="scope.row.qty" :style='{ "width": "100%" }'
														placeholder='请输入' clearable required>
													</el-input>
												</el-form-item>
											</template>
										</el-table-column>
										<el-table-column v-if="!readOnly" label="操作" width="50">
											<template slot-scope="scope">
												<el-button size="mini" type="text" class="SHZY-table-delBtn"
													@click="handleDelMaterial(scope.$index)">删除</el-button>
											</template>
										</el-table-column>
									</el-table>
								</el-form>
								<div v-if="!readOnly" class="table-actions" @click="handleAddMaterial()">
									<el-button type="text" icon="el-icon-plus">新增</el-button>
								</div>
							</el-form-item>
						</el-col>
					</el-form>
				</el-row>
			</div>
		</div>
	</transition>
</template>
<script>
import { getWorkorderInfo, createWorkorder, updateWorkorder } from '@/api/q1/business/workOrder'
import { getMaterialAll } from '@/api/q1/basedata/material';
export default {
	components: {},
	props: [],
	data() {
		const planStartTimeValidator = (rule, value, callback) => {
			if (value.length == 0) {
				callback(new Error("请选择计划开始时间"));
			} else {
				let date1 = new Date(this.dataForm.planStartTime);
				let date2 = new Date(this.dataForm.planEndTime);
				if (date1.getTime() > date2.getTime()) {
					callback(new Error("计划开始时间必须小于或等于计划完成时间"));
				} else {
					callback();
				}
			}
		};
		const planEndTimeValidator = (rule, value, callback) => {
			if (value.length == 0) {
				callback(new Error("请选择计划完成时间"));
			} else {
				let date1 = new Date(this.dataForm.planStartTime);
				let date2 = new Date(this.dataForm.planEndTime);
				console.log(date1.getTime(),date2.getTime())
				if (date1.getTime() > date2.getTime()) {
					callback(new Error("计划完成时间必须大于或等于计划开始时间"));
				} else {
					callback();
				}
			}
		};
		const materialIdValidator = (rule, value, callback) => {
			if (!value || value.materialId.trim().length == 0) {
				callback(new Error("请选择物料"));
			} else {
				console.log(this.dataForm.qmsBusiWorkorderdetailList.filter(x => x.materialId == value.materialId))
				if (this.dataForm.qmsBusiWorkorderdetailList.filter(x => x.materialId == value.materialId).length > 1) {
					callback(new Error("物料重复添加"));
				} else {
					callback();
				}
			}
		};
		return {
			btnLoading: false,
			loading: false,
			visible: false,
			readOnly: false,
			dataForm: {
				id: "",
				code: "",
				type: "",
				materialId: "",
				qty: "",
				unit: "",
				planStartTime: "",
				planEndTime: "",
				remark: "",
				status: 0,
				qmsBusiWorkorderdetailList: [],
			},
			rules: {
				code: [
					{
						required: true,
						message: '请输入工单号',
						trigger: '"blur"'
					},
				],
				type: [
					{
						required: true,
						message: '请输入工单类型',
						trigger: '"change"'
					},
				],
				materialId: [
					{
						required: true,
						message: '请输入物料ID',
						trigger: '"change"'
					},
				],
				qty: [
					{
						required: true,
						message: '请输入数量',
						trigger: '"blur"'
					},
					{
						pattern: /^\d+$/,
						message: '请输入正确的数字',
						trigger: '"blur"'
					},
				],
				planStartTime: [{ required: true, validator: planStartTimeValidator, trigger: '"blur"' }],
				planEndTime: [{ required: true, validator: planEndTimeValidator, trigger: '"blur"' }],
			},
			tableRules: {
				materialId: [{ required: true, validator: materialIdValidator, trigger: '"blur"' }],
				qty: [
					{ required: true, message: '请输入用量', trigger: '"blur"' },
					{ pattern: /^\d+$/, message: '请输入正确的数字', trigger: '"blur"' },
				],
			},
			workOrderTypeData: [],
			materialData: [],
			unitData: [],
		}
	},
	computed: {},
	watch: {},
	created() {
		this.getDictionaryData()
	},
	mounted() {
	},
	methods: {
		getDictionaryData() {
			this.$store.dispatch('base/getDictionaryData', { sort: 'workOrderType' }).then((res) => {
				this.workOrderTypeData = res
			})
			this.$store.dispatch('base/getDictionaryData', { sort: 'MaterialUnit' }).then((res) => {
				this.unitData = res
			})
		},
		goBack() {
			this.$emit('refresh')
		},
		init(id) {
			this.dataForm.id = id || 0;
			this.visible = true;
			this.$nextTick(() => {
				this.$refs['elForm'].resetFields();
				getMaterialAll().then(res => {
					this.materialData = res.data.list;
				});
				this.dataForm.qmsBusiWorkorderdetailList = [];
				if (this.dataForm.id) {
					getWorkorderInfo(this.dataForm.id).then(res => {
						this.dataForm = res.data;
						if (this.dataForm.status != 0) {
							this.readOnly = true
						}
					})
				}
			});
		},
		dataFormSubmit(status) {
			this.$refs['elForm'].validate((valid) => {
				if (valid) {
					this.$refs['tableForm'].validate((valid) => {
						if (valid) {
							this.btnLoading = true;
							this.dataForm.status = status
							const formMethod = !this.dataForm.id ? createWorkorder : updateWorkorder;
							formMethod(this.dataForm).then((res) => {
								this.btnLoading = false;
								this.$message({
									message: res.msg,
									type: 'success',
									duration: 1000,
									onClose: () => {
										this.visible = false,
											this.$emit('refresh', true)
									}
								})
							}).catch((res) => {
								this.btnLoading = false;
							})

						}
					})
				}
			})
		},
		handleAddMaterial() {
			let item = {
				materialId: "",
				qty:  "",
			}
			this.dataForm.qmsBusiWorkorderdetailList.push(item)
		},
		handleDelMaterial(index) {
			this.dataForm.qmsBusiWorkorderdetailList.splice(index, 1);
		},
	}
}
</script>
